import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hj_crm/const/constant.dart';
import 'package:hj_crm/entity/pagination.dart';
import 'package:hj_crm/entity/user_info.dart';
import 'package:hj_crm/form/conference_list.dart';
import 'package:hj_crm/form/order_list.dart';
import 'package:hj_crm/form/outbound_list.dart';
import 'package:hj_crm/form/user_form.dart';
import 'package:hj_crm/http/request_repository.dart';
import 'package:hj_crm/utils/perms_check.dart';

import 'package:hj_crm/widget/load_more_widget.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

typedef UsersChanged = void Function(List<UserInfo> userData);

/// 用户列表
class UserListWidget extends StatefulWidget {
  final RefreshAction refreshAction;

  const UserListWidget({
    super.key,
    required this.refreshAction,
  });

  @override
  State<UserListWidget> createState() => _UserListState();
}

class _UserListState extends State<UserListWidget> {
  List<UserInfo> users = <UserInfo>[];
  UsersDataSource? dataSource;

  Pagination? pagination;

  RequestRepository repository = Get.find<RequestRepository>();

  // 编辑用户
  final bool _canUpdate = PermsCheck.customerUpdate();
  // 删除用户
  final bool _canDelete = PermsCheck.customerDelete();
  // 用户订单菜单
  final bool _showOrder = PermsCheck.customerOrderPage();
  // 参会情况菜单
  final bool _showConference = PermsCheck.customerConferencePage();
  // 出库管理菜单
  final bool _showDeliver = PermsCheck.userDeliverPage();

  bool canSwiper = true;

  int maxOffset = 180;

  @override
  void initState() {
    super.initState();

    canSwiper = _canDelete || _showOrder || _showConference || _showDeliver;
    maxOffset = _show(_showOrder) * 60 + _show(_showConference) * 60 + _show(_showDeliver) * 60;
    widget.refreshAction(refresh);
    refresh();
  }

  refresh() {
    repository.userList(
      success: (data) {
        setState(() {
          users = data.data;
          pagination = data.pagination;
          dataSource = UsersDataSource(
            userData: users,
            pagination: pagination,
            dataChanged: (userData) => users = userData,
          );
        });
      },
    );
  }

  int _show(bool show) => show ? 1 : 0;

  @override
  void dispose() {
    dataSource?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return dataSource == null
        ? Center(
            child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation(Colors.deepPurple)))
        : SafeArea(
            child: SfDataGrid(
              source: dataSource!,
              columnWidthMode: ColumnWidthMode.fill,
              onCellTap: (details) {
                if (_canUpdate == false) {
                  return;
                }
                if (details.rowColumnIndex.rowIndex == 0) {
                  return;
                }
                Get.to(() => UserFormWidget(uId: users[details.rowColumnIndex.rowIndex - 1].id))
                    ?.then((value) {
                  if (value == true) refresh();
                });
              },
              allowSwiping: canSwiper,
              swipeMaxOffset: maxOffset.toDouble(),
              allowPullToRefresh: true,
              loadMoreViewBuilder: loadMoreBuilder,
              onSwipeStart: (swipeStartDetails) {
                if (canSwiper == false) {
                  return false;
                }
                if (swipeStartDetails.swipeDirection == DataGridRowSwipeDirection.endToStart) {
                  swipeStartDetails.setSwipeMaxOffset(maxOffset.toDouble());
                } else {
                  swipeStartDetails.setSwipeMaxOffset(_canDelete ? 100 : 0);
                }
                return true;
              },
              startSwipeActionsBuilder: (context, dataGridRow, rowIndex) {
                return _canDelete
                    ? InkWell(
                        child: Container(
                          height: double.infinity,
                          width: 100,
                          alignment: Alignment.center,
                          color: Colors.red,
                          child: Text('删除'),
                        ),
                        onTap: () {
                          repository.deleteUser(
                            ids: [users[rowIndex].id!],
                            success: (data) {
                              // users.removeAt(rowIndex);
                              // dataGridRow.getCells().removeAt(rowIndex);
                              dataSource?.deleteRow(rowIndex);
                            },
                          );
                        },
                      )
                    : null;
              },
              endSwipeActionsBuilder: (context, dataGridRow, rowIndex) {
                return Row(
                  children: [
                    _showConference
                        ? InkWell(
                            child: Container(
                              height: double.infinity,
                              width: 60,
                              alignment: Alignment.center,
                              color: Colors.lightBlue,
                              child: Text('参会记录'),
                            ),
                            onTap: () {
                              Get.to(() => ConferenceListWidget(uId: users[rowIndex].id!));
                            },
                          )
                        : Container(),
                    _showOrder
                        ? InkWell(
                            child: Container(
                              width: 60,
                              height: double.infinity,
                              alignment: Alignment.center,
                              color: Colors.lightGreen,
                              child: Text('订单记录'),
                            ),
                            onTap: () {
                              Get.to(() => OrderListWidget(uId: users[rowIndex].id!));
                            },
                          )
                        : Container(),
                    _showDeliver
                        ? InkWell(
                            child: Container(
                              width: 60,
                              height: double.infinity,
                              alignment: Alignment.center,
                              // color: Colors.orange[300],
                              color: Colors.amber,
                              child: Text('出库记录'),
                            ),
                            onTap: () {
                              Get.to(() => OutboundListWidget(uId: users[rowIndex].id!));
                            },
                          )
                        : Container(),
                  ],
                );
              },
              columns: <GridColumn>[
                GridColumn(
                    columnName: 'name',
                    label: Container(
                        padding: EdgeInsets.all(16.0),
                        alignment: Alignment.center,
                        child: Text(
                          '姓名',
                        ))),
                GridColumn(
                  columnName: 'age',
                  label: Container(
                      padding: EdgeInsets.all(8.0), alignment: Alignment.center, child: Text('年龄')),
                ),
                GridColumn(
                    columnName: 'address',
                    label: Container(
                        padding: EdgeInsets.all(8.0),
                        alignment: Alignment.center,
                        child: Text(
                          '详细地址',
                          overflow: TextOverflow.ellipsis,
                        ))),
                GridColumn(
                  columnName: 'health',
                  label: Container(
                      padding: EdgeInsets.all(8.0),
                      alignment: Alignment.center,
                      child: Text('健康状况')),
                ),
              ],
            ),
          );
  }
}

/// An object to set the employee collection data source to the datagrid. This
/// is used to map the employee data to the datagrid widget.
class UsersDataSource extends DataGridSource {
  /// Creates the employee data source class with required details.
  UsersDataSource({
    required List<UserInfo> userData,
    Pagination? pagination,
    required UsersChanged dataChanged,
  }) {
    _infos = userData;
    _pagination = pagination;
    _dataChanged = dataChanged;
    _usersData = userData
        .map<DataGridRow>((e) => DataGridRow(cells: [
              DataGridCell<String>(columnName: 'name', value: e.name),
              DataGridCell<int>(columnName: 'age', value: e.age),
              DataGridCell<String>(columnName: 'address', value: e.address),
              DataGridCell<String>(columnName: 'health', value: e.healthStatus),
            ]))
        .toList();
  }

  UsersChanged? _dataChanged;

  List<DataGridRow> _usersData = [];

  int _page = 1;

  Pagination? _pagination;

  List<UserInfo> _infos = [];

  @override
  List<DataGridRow> get rows => _usersData;

  RequestRepository repository = Get.find<RequestRepository>();

  bool get canLoadMore {
    if (_pagination == null) {
      return true;
    }
    if (_pagination!.size! * _page > _pagination!.total!) {
      return false;
    }
    return true;
  }

  void deleteRow(int index) {
    _infos.removeAt(index);
    _usersData.removeAt(index);
    _pagination = Pagination(
      size: _pagination!.size,
      total: (_pagination!.total! - 1),
      page: _page,
    );
    notifyListeners();
  }

  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((e) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(8.0),
        child: Text(e.value.toString()),
      );
    }).toList());
  }

  @override
  Future<void> handleRefresh() {
    _page = 1;
    repository.userList(
      success: (data) {
        _infos = data.data;
        _pagination = data.pagination;
        _dataChanged?.call(_infos);
        _usersData = _infos
            .map<DataGridRow>((e) => DataGridRow(cells: [
                  DataGridCell<String>(columnName: 'name', value: e.name),
                  DataGridCell<int>(columnName: 'age', value: e.age),
                  DataGridCell<String>(columnName: 'address', value: e.address),
                  DataGridCell<String>(columnName: 'health', value: e.healthStatus),
                ]))
            .toList();
        notifyListeners();
      },
    );

    return super.handleRefresh();
  }

  @override
  Future<void> handleLoadMoreRows() async {
    if (!canLoadMore) {
      return super.handleLoadMoreRows();
    }
    _page += 1;
    repository.userList(
      page: _page,
      success: (data) {
        _infos.addAll(data.data);
        _pagination = data.pagination;
        _dataChanged?.call(_infos);
        _usersData.addAll(data.data
            .map<DataGridRow>((e) => DataGridRow(cells: [
                  DataGridCell<String>(columnName: 'name', value: e.name),
                  DataGridCell<int>(columnName: 'age', value: e.age),
                  DataGridCell<String>(columnName: 'address', value: e.address),
                  DataGridCell<String>(columnName: 'health', value: e.healthStatus),
                ]))
            .toList());
        notifyListeners();
      },
    );
    return super.handleLoadMoreRows();
  }
}
